package pub.wkq.thread;


import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class Test {
    public static void main(String[] args) {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 10, 60, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(5),
                new MyThreadFactory("io-pool"));
        for (int i = 0; i < 10; i++) {
            executor.execute(()->{
                System.out.println(" i " + Thread.currentThread().getName());
            });
        }


    }
}

class MyThreadFactory implements ThreadFactory {
    private final String namePrefix;
    private final AtomicInteger nextId = new AtomicInteger(1);

    /**
     * 定义线程名称，在使用 jstack 来排查问题时，非常有帮助
     *
     * @param whatFeatureOfGroup
     */
    public MyThreadFactory(String whatFeatureOfGroup) {
        this.namePrefix = "From myThreadFactory: " + whatFeatureOfGroup + "-worker-";
    }

    @Override
    public Thread newThread(Runnable task) {
        String name = namePrefix + nextId.getAndIncrement();
        Thread thread = new Thread(null, task, name, 0);
        return thread;
    }
}